import { dialog, app } from 'electron'
import EventRoute from '../EventRoute'
import store from '../../store/index'
import ShortcutManager from '../../utils/shortcutManager'
const routers: EventRoute[] = []

// 显示浏览器视图
routers.push(
  new EventRoute('show-browser-view', async (api) => {
    api.browserViewWindow.showBrowserView()
  })
)

// 隐藏浏览器视图
routers.push(
  new EventRoute('hide-browser-view', async (api) => {
    api.browserViewWindow.hideBrowserView()
  })
)

// 默认设置
function getDefaultApplicationSettings() {
  return {
    shortcuts: {
      shortcut1: '',
      shortcut2: '',
      shortcut3: '',
      shortcut4: ''
    },
    recordingPath: app.getPath('videos')
  }
}

// 读取设置（用于初始化渲染端）
routers.push(
  new EventRoute('get-application-settings', async () => {
    const settings = (store.get('applicationSettings') as any) || getDefaultApplicationSettings()
    const def = getDefaultApplicationSettings()
    const merged = {
      shortcuts: { ...def.shortcuts, ...(settings.shortcuts || {}) },
      recordingPath: settings.recordingPath || def.recordingPath
    }
    return merged
  })
)

// 选择录屏保存目录（仅返回选择结果，不落库）
routers.push(
  new EventRoute('pick-recording-path', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory', 'createDirectory']
    })
    if (result.canceled || !result.filePaths?.length) return null
    return result.filePaths[0]
  })
)

// 保存录屏目录（立即持久化）
routers.push(
  new EventRoute('save-recording-path', async (_api, { data }) => {
    const path = (data && data.path) || ''
    const prev = (store.get('applicationSettings') as any) || getDefaultApplicationSettings()
    store.set('applicationSettings', {
      shortcuts: prev.shortcuts || getDefaultApplicationSettings().shortcuts,
      recordingPath: path || prev.recordingPath || getDefaultApplicationSettings().recordingPath
    })
    return { success: true }
  })
)

// 单个快捷键校验（与已注册冲突、与其他配置项重复）
routers.push(
  new EventRoute('validate-single-shortcut', async (_api, { data }) => {
    const key: string = data?.key || ''
    const accelerator: string = (data?.accelerator || '').trim()
    if (!key) return { ok: false, reason: 'invalid_key' }
    if (!accelerator)
      return { ok: true, duplicate: false, conflict: false, duplicates: [], conflicts: [] }

    const sm = ShortcutManager.getInstance()
    // 与当前已注册冲突
    const conflict = sm.isRegistered(accelerator)
    const conflicts = conflict ? [accelerator] : []

    // 与其他已配置（store）重复
    const settings = (store.get('applicationSettings') as any) || getDefaultApplicationSettings()
    const shortcuts = settings.shortcuts || {}
    const duplicates: string[] = []
    Object.keys(shortcuts).forEach((k) => {
      if (k !== key) {
        const v = (shortcuts[k] || '').trim()
        if (v && v.toLowerCase() === accelerator.toLowerCase()) {
          duplicates.push(v)
        }
      }
    })

    const ok = !conflict && duplicates.length === 0
    return { ok, duplicate: duplicates.length > 0, conflict, duplicates, conflicts }
  })
)

// 应用当前配置中的所有快捷键（先清空，再逐个注册与功能绑定）
routers.push(
  new EventRoute('apply-shortcuts', async (api) => {
    const sm = ShortcutManager.getInstance()
    sm.unregisterAll()

    const settings = (store.get('applicationSettings') as any) || getDefaultApplicationSettings()
    const sc = settings.shortcuts || {}
    const failed: string[] = []
    const seen = new Set<string>()

    function registerOne(acc: string, handler: () => void) {
      if (!acc) return
      const key = acc.toLowerCase()
      if (seen.has(key)) return
      seen.add(key)
      const ok = sm.register(acc, handler)
      if (!ok) failed.push(acc)
    }

    // 快捷键1：启动AI助手（显示 AiIcon 窗口）
    registerOne(sc.shortcut1, () => {
      api.aiIconWindow.show()
    })

    // 快捷键2：触发截图
    registerOne(sc.shortcut2, () => {
      api.aiIconWindow.triggerScreenshot()
    })

    // 快捷键3：启动屏幕录制（确保窗口存在，再开始录制）
    registerOne(sc.shortcut3, () => {
      api.screenRecorderWindow.create()
      api.screenRecorderWindow.startRecording()
    })

    // 快捷键4：打开问答界面（打开 AiChat 窗口并隐藏图标窗口）
    registerOne(sc.shortcut4, () => {
      const position = api.aiIconWindow.getPosition()
      api.aiChatWindow.showAiChat(position[0], position[1])
      api.aiChatWindow.show()
      api.aiIconWindow.hide()
    })

    return { success: failed.length === 0, failed }
  })
)

// 保存单个快捷键（落库后立即应用）
routers.push(
  new EventRoute('save-application-shortcut', async (_api, { data }) => {
    const key: string = data?.key
    const accelerator: string = (data?.accelerator || '').trim()
    if (!['shortcut1', 'shortcut2', 'shortcut3', 'shortcut4'].includes(key)) {
      return { success: false, reason: 'invalid_key' }
    }

    // 更新 store
    const prev = (store.get('applicationSettings') as any) || getDefaultApplicationSettings()
    const shortcuts = {
      ...(prev.shortcuts || getDefaultApplicationSettings().shortcuts),
      [key]: accelerator
    }
    store.set('applicationSettings', {
      shortcuts,
      recordingPath: prev.recordingPath || getDefaultApplicationSettings().recordingPath
    })

    // 重新应用全部快捷键，确保即时生效
    // const applyShortcutsRoute = routers.find((r) => r.name === 'apply-shortcuts')
    // if (!applyShortcutsRoute) throw new Error('找不到apply-shortcuts路由')
    // const result = await applyShortcutsRoute.handler(api, { data: null })
    // return result
    return true
  })
)

export default routers
